package com.zzhrtech.wgzx_cityzen.ui.contact;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
import com.squareup.picasso.Picasso;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.BaseActivity;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.beans.contact.CodeDhBean;
import com.zzhrtech.wgzx_cityzen.beans.contact.JifenGoodsBean;
import com.zzhrtech.wgzx_cityzen.beans.contact.JifenGoodsDetailBean;
import com.zzhrtech.wgzx_cityzen.beans.me.LoginBean;
import com.zzhrtech.wgzx_cityzen.beans.task.BaseBean;
import com.zzhrtech.wgzx_cityzen.view.CustomProgress;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class JifenDetailActivity extends BaseActivity {

    private ImageView iv_goods;
    private TextView tv_name,tv_points,tv_num,tv_allpoint;

    private Button btn_duihuan;
//    private MaterialDialog progress;

    private CustomProgress proDialog;
    private String goodid,goodnum,myAllNum;
    private WebView webView;

    private int screenWidth;
    private JifenGoodsDetailBean detailBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jifen_detail);

        toolbar.setNavigationIcon(R.mipmap.ic_close);

        goodid = getIntent().getStringExtra("goodid");

        proDialog = CustomProgress.show(this,true,null);
        proDialog.show();

        initView();

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        screenWidth = metric.widthPixels;

        httpGetInfo();
        httpGetGoodDetail();

    }

    private void initView(){

        webView = (WebView) findViewById(R.id.webView);
        WebSettings settings = webView.getSettings();

        settings.setJavaScriptEnabled(true);

        settings.setNeedInitialFocus(false);

        settings.setSupportZoom(true);

        settings.setLoadWithOverviewMode(true);//适应屏幕

        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        settings.setLoadsImagesAutomatically(true);//自动加载图片

        settings.setCacheMode(WebSettings.LOAD_DEFAULT |WebSettings.LOAD_CACHE_ELSE_NETWORK);


        iv_goods = (ImageView) findViewById(R.id.iv_goods);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_points = (TextView) findViewById(R.id.tv_points);
        tv_num = (TextView) findViewById(R.id.tv_num);
        btn_duihuan = (Button) findViewById(R.id.btn_duihuan);
        tv_allpoint = (TextView) findViewById(R.id.tv_allpoint);

        btn_duihuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.parseInt(myAllNum) < Integer.parseInt(goodnum)){
                    showToast("积分不足!");
                }else {

                    if (detailBean.getData().getGood_type() != null) {
                        if (detailBean.getData().getGood_type().equals("1")) {
                            new MaterialDialog.Builder(JifenDetailActivity.this)
                                    .title("确认兑换")
                                    .customView(R.layout.dialog_jifendh, true)
                                    .positiveText("确定")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            View view = dialog.getCustomView();
                                            EditText mNameView = (EditText) view.findViewById(R.id.name);
                                            EditText mPhoneView = (EditText) view.findViewById(R.id.phone);
//                                            EditText mAddressView = (EditText) view.findViewById(R.id.address);

                                            if (mNameView.getText().toString().isEmpty()) {
                                                showToast("填写姓名");
                                            } else {
                                                httpGetGoods(mNameView.getText().toString(), mPhoneView.getText().toString());
                                            }
                                        }
                                    })
                                    .show();
                        }else {

                            new MaterialDialog.Builder(JifenDetailActivity.this)
                                    .title("确认兑换？")
                                    .positiveText("确定")
                                    .negativeText("取消")
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            httpGetGoodsMa();
                                        }
                                    }).show();


                        }
                    }
                }
            }
        });
    }


    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0){

                proDialog.dismiss();
                detailBean = (JifenGoodsDetailBean) msg.obj;

                Picasso.with(JifenDetailActivity.this)
                        .load(detailBean.getData().getGood_imgth())
                        .resize(screenWidth,screenWidth * 348 / 690)
                        .centerCrop()
                        .into(iv_goods);

//                webView.loadUrl(data.getLink());

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Document doc_dis = Jsoup.connect(detailBean.getLink()).get();

                            Elements ele_img = doc_dis.getElementsByTag("img");

                            doc_dis.attr("background-color","white");

                            if(ele_img.size() !=0) {
                                for(Element e_Img:ele_img) {
                                    e_Img.attr("width","100%");
                                    //一定要设置 auto 不要控制其高度，让其自己跟随宽度变化情况调整
                                    e_Img.attr("height","auto");

                                    String name =  e_Img.attr("src");
                                    e_Img.attr("src","http://ccwg.zzhrtech.com/" + name);

                                }
                            }

                            Message message = new Message();
                            message.obj = doc_dis.toString();
                            message.what = 2;
                            mHandler.sendMessage(message);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();




                tv_name.setText(detailBean.getData().getGood_name());
                goodnum = detailBean.getData().getGood_num();
                tv_points.setText("所需积分：" + goodnum);
                tv_num.setText(detailBean.getData().getInventory());


            }else if (msg.what == 1){
                showToast("兑换成功");
                setResult(RESULT_OK);
                finish();
            }else if (msg.what == 2){
                String newHtmlContent = (String) msg.obj;
                webView.loadDataWithBaseURL(null,newHtmlContent,"text/html","utf-8",null);
            }else if (msg.what == 3) {
                LoginBean.Data logindata = (LoginBean.Data) msg.obj;
                myAllNum = logindata.getNum();
                tv_allpoint.setText("（我的积分：" + myAllNum + "）");
            }else if (msg.what == 4){

                CodeDhBean bean = (CodeDhBean) msg.obj;

                new MaterialDialog.Builder(JifenDetailActivity.this)
                        .title("您的兑换码为")
                        .content(bean.getCodex() + "  (可在兑换记录中查看)")
                        .positiveText("确定")
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                setResult(RESULT_OK);
                                finish();
                            }
                        })
                        .show();

            }

            return false;
        }
    });


    private void httpGetInfo() {

        Map<String, String> params = new HashMap<String, String>();
        params.put("citizen_id", getCache().getAsString(Constans.keyUid));
        GsonRequest<LoginBean> gsonRequest = new GsonRequest<LoginBean>(com.android.volley.Request.Method.POST, Constans.HTTP_USERINFO, LoginBean.class, params, new com.android.volley.Response.Listener<LoginBean>() {
            @Override
            public void onResponse(LoginBean response) {
                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 3;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                } else {
                    showToast(response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====", error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }


    private void httpGetGoodDetail(){

        Map<String,String> map = new HashMap<String, String>();
        map.put("good_id",goodid);
        GsonRequest<JifenGoodsDetailBean> gsonRequest = new GsonRequest<JifenGoodsDetailBean>(Request.Method.POST, Constans.HTTP_GOODSDETAIL, JifenGoodsDetailBean.class, map, new com.android.volley.Response.Listener<JifenGoodsDetailBean>() {
            @Override
            public void onResponse(JifenGoodsDetailBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 0;
                    message.obj = response;
                    mHandler.sendMessage(message);
                }else {
                    proDialog.dismiss();
                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                proDialog.dismiss();

                Log.d("result=====",error + "");
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }


    private void httpGetGoods(String name,String phone){

        Map<String,String> map = new HashMap<String, String>();
        map.put("citizen_id",getCache().getAsString(keyUid));
        map.put("good_id",goodid);
        map.put("truename",name);
        map.put("phone",phone);
        map.put("ac_id",getIntent().getStringExtra("acid"));
        GsonRequest<BaseBean> gsonRequest = new GsonRequest<BaseBean>(Request.Method.POST, Constans.HTTP_GOODSGET, BaseBean.class, map, new com.android.volley.Response.Listener<BaseBean>() {
            @Override
            public void onResponse(BaseBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 1;
                    mHandler.sendMessage(message);
                }else {

                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Log.d("result=====",error + "");
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private void httpGetGoodsMa(){

        Map<String,String> map = new HashMap<String, String>();
        map.put("citizen_id",getCache().getAsString(keyUid));
        map.put("good_id",goodid);
        map.put("ac_id",getIntent().getStringExtra("acid"));
        GsonRequest<CodeDhBean> gsonRequest = new GsonRequest<CodeDhBean>(Request.Method.POST, Constans.HTTP_GOODSGETX, CodeDhBean.class, map, new com.android.volley.Response.Listener<CodeDhBean>() {
            @Override
            public void onResponse(CodeDhBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 4;
                    message.obj = response;
                    mHandler.sendMessage(message);
                }else {
                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Log.d("result=====",error + "");
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

}
